package com.band.service.impl;

import com.band.entity.*;
import com.band.exception.ClazzStatuException;
import com.band.mapper.ClazzMapper;
import com.band.mapper.StudentMapper;
import com.band.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;
    /**
     * 获取班级列表
     * @param param 查询参数
     * @return 班级列表
     */
    @Override
    public PageBean list(ClazzQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        //2.调用mapper的列表查询方法
        List<Clazz> clazzList = clazzMapper.list(param);
        //3.封装PageBean对象并返回
        Page p = (Page) clazzList;
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 删除班级
     * @param id
     */

    @Override
    public void delete(Integer id) {
        List<Student> studentList =  studentMapper.selectByClazzId(id);
        //调用Mapper删除
        if (!CollectionUtils.isEmpty(studentList)){
            throw new ClazzStatuException("该班级下有学生");
        }
        else {
            clazzMapper.delete(id);
        }

    }

    /**
     * 新增班级
     * @param clazz
     */
    @Override
    public void insert(Clazz clazz) {
        //1.补充基本信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        //2.调用Mapper新增
        clazzMapper.insert(clazz);

    }

    /**
     * 数据回显
     * @param id
     * @return
     */
    @Override
    public Clazz select(Integer id) {

        return clazzMapper.select(id);
    }

    /**
     * 修改班级
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        //1.补充信息
        clazz.setUpdateTime(LocalDateTime.now());
        //2.调用Mapper修改
        clazzMapper.update(clazz);
    }

    /**
     * 获取全部班级列表
     * @return
     */
    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }

    @Override
    public ClazzCountOption studentCountData() {
        List<Map> list = clazzMapper.studentCountData();
        List<Object> clazzList = list.stream().map(item -> item.get("name")).toList();
        List<Object> dataList = list.stream().map(item -> item.get("sum")).toList();

        return new ClazzCountOption(clazzList,dataList);
    }
}
